package luke4fun.wheresmymoney.fragments;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;

import luke4fun.wheresmymoney.R;
import luke4fun.wheresmymoney.adapter.ColorChooserAdapter;
import luke4fun.wheresmymoney.adapter.list.BasicAdapter;
import luke4fun.wheresmymoney.adapter.list.impl.CategoryMgrListAdapter;
import luke4fun.wheresmymoney.bean.CategoryBean;
import luke4fun.wheresmymoney.common.CommonConstants;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.CategoryDAO;
import luke4fun.wheresmymoney.db.DBConstants;
import luke4fun.wheresmymoney.service.async.CategoryAsyncTask;

public class CategoryFragment extends Fragment {
	
	private Context context;
	private ListView categoryListView;
	private LinearLayout newCategoryLayout;
	private Spinner colorChooser;
	private EditText newCategoryText;
	private ImageButton addBtn;
	
	private BasicAdapter<CategoryBean> adapter;
	private ColorChooserAdapter colorAdapter;
	private AccDBHelper dbHelper;
	private CategoryDAO categoryDao = CategoryDAO.getInstance();

	public static CategoryFragment getInstance() {
		return new CategoryFragment();
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		context = getActivity();

		// init views
		View v = inflater.inflate(R.layout.fragment_category, container, false);
		initView(v);
		
		colorAdapter = new ColorChooserAdapter(getActivity(), colorChooser, CommonConstants.COLOR, false);
		colorChooser.setAdapter(colorAdapter);
		
		addBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = dbHelper.getWritableDatabase();
				ContentValues cv = new ContentValues();
				cv.put(DBConstants.ITEM_NAME, newCategoryText.getText().toString());
				cv.put(DBConstants.CATEGORY_COLOR, (Integer) colorChooser.getSelectedItem());
				categoryDao.insertCategory(db, cv);
				db.close();
				
				refresh();
				hideKeyboard();
				newCategoryText.setText("");
			}
		});
		
        if (adapter == null) {
        	adapter = new CategoryMgrListAdapter(context); 
        }
        
        categoryListView.setAdapter(adapter);
        // add onScrollListener to clear focus on EditText
        categoryListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			}

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

				// if it starts to scroll, clear focus
				if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
					View v = categoryListView.getFocusedChild();
					if (v != null) {
						v.clearFocus();
						hideKeyboard();
					}
				}
			}
        });
        
        return v;
    }
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		dbHelper = new AccDBHelper(context);
	}
	
	@Override
	public void onStart() {
		super.onStart();
	}

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(getString(R.string.title_category));
        refresh();
    }
	
	@Override
	public void onPause() {
		// clear focus on EditText
		View v = categoryListView.getFocusedChild();
		if (v != null) {
			v.clearFocus();
		}
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
	
	private void initView(View v) {
		categoryListView = (ListView) v.findViewById(R.id.category_list);
		newCategoryLayout = (LinearLayout) v.findViewById(R.id.new_category);
		colorChooser = (Spinner) newCategoryLayout.findViewById(R.id.color_chooser);
		newCategoryText = (EditText) newCategoryLayout.findViewById(R.id.category_txt);
		addBtn = (ImageButton) newCategoryLayout.findViewById(R.id.add);
		addBtn.setVisibility(View.VISIBLE);
	}
	
	private void refresh() {
		if (context != null) {
			new CategoryAsyncTask(context, this.adapter).execute();
		}
	}
	
	public void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(newCategoryText.getWindowToken(), 0);
	}
}
